package self;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Transaction;

import java.text.Collator;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by 刘万祥 on 2017/5/14 0014.
 */
public class Chapter05 {

    private final String recent_key_prefix = "recent:";

    public static void main(String[] args) {
        new Chapter05().run();
    }

    private void run() {
        Jedis conn = new Jedis("localhost");
        conn.select(15);


        testLogRecent(conn);
        testLogCommon(conn);
    }

    private void testLogRecent(Jedis conn) {

        String logInfo = "info";
        DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < 5; i++) {
            String  dest= recent_key_prefix +"test"+":"+logInfo;
            Pipeline pipeline = conn.pipelined();
            String str = "message " + i;
            pipeline.lpush(dest, timeFormat.format(new Date()) + " " + str);
//           只包含最新的100条数据
            pipeline.ltrim(dest, 0, 99);
            pipeline.sync();
        }

        List<String> recents = conn.lrange(recent_key_prefix + "test" + ":" + logInfo, 0, -1);
        System.out.println(recents.size());
    }

    private void testLogCommon(Jedis conn) {

        for (int i = 0; i < 5; i++) {
            logCommon(conn,"test", "message-" + i,5000);
        }
    }

    private void logCommon(Jedis conn, String name, String message, int timeout) {
        String logInfo = "info";

        String dest = "common:" + name + ":" + logInfo;
        String startKey = dest + ":start";

        long end = System.currentTimeMillis() + timeout;
        DateFormat hourFormat = new SimpleDateFormat("yyyy-MM-dd HH");
        while (System.currentTimeMillis() < end) {

            conn.watch(startKey);
            String existing = conn.get(startKey);
            String hourStart = hourFormat.format(new Date());

            Transaction trans = conn.multi();
            if (existing != null && Collator.getInstance().compare(existing, hourStart) < 0) {
                trans.rename(dest, dest + ":last");
            }

        }
    }
}
